/*
 RLEditRecyclingRunViewController.h
 Date Created: February 18, 2010
 
 Author: Karol Krizka <kkrizka@gmail.com>
 
 Copyright (C) 2010 Green-Power
 
 URL: http://code.google.com/p/green-power
 
 This program is free software; you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation; either version 3 of the License, or
 (at your option) any later version.
 
 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.
 
 You should have received a copy of the GNU General Public License
 along with this program; if not, write to the Free Software
 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 
 $Id$
 */

#import "RLEditRecyclingRunViewController.h"

#import "RLStyleFormatter.h"
#import "RLRecyclableType.h"
#import "RLRecyclableItemButton.h"
#import "RLEditRecyclableItemViewController.h"

#import "GPNavigationBarViewController.h"

@implementation RLEditRecyclingRunViewController

@synthesize dateTimeButton;
@synthesize editItemArea;
@synthesize moneyEarnedLabel;

- (RLEditRecyclingRunViewController *)initWithRun:(RLRecyclingRun *)runArg {
  self=[super init];
  if( self ) {
    run=runArg;
  }
  return self;
}

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
  [super viewDidLoad];
  
  [self setTitle:@"Edit Recycling Run"];
  
  [self setupEditItemButtons];
  [self updateDateTimeButton];
  [self updateMoneyEarnedLabel];
}

- (void)didReceiveMemoryWarning {
	// Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
	
	// Release any cached data, images, etc that aren't in use.
}

- (void)updateMoneyEarnedLabel {
  self.moneyEarnedLabel.text=[RLStyleFormatter formatMonetaryValue:run.moneyEarned];
}

- (void)updateDateTimeButton {
  [dateTimeButton setTitle:[RLStyleFormatter formatDate:run.dateTime] forState:UIControlStateNormal];

}

- (void)setupEditItemButtons {
  NSArray *types=[RLRecyclableType listOfficialTypes];
  
  NSUInteger MAXBUTTONSPERROW=2;
  CGRect editItemAreaFrame=[editItemArea frame];
  NSUInteger buttonWidth=editItemAreaFrame.size.width/MAXBUTTONSPERROW-10;
  NSUInteger buttonHeight=buttonWidth; // Make the buttons square
  
  NSMutableDictionary *typeNamesInRow=[NSMutableDictionary dictionaryWithCapacity:types.count]; // What row are specific item type names in
  NSMutableDictionary *numTypeNamesInRow=[NSMutableDictionary dictionaryWithCapacity:types.count]; // How many of item names are already added
  
  for(RLRecyclableType *type in types)
  {
    RLRecyclableItem *item=[run itemForUniqueName:type.uniqueName];
    RLRecyclableItemButton *button=[[RLRecyclableItemButton alloc] initWithItem:item];
    [button addTarget:self
               action:@selector(editItem:)
     forControlEvents:UIControlEventTouchUpInside];
    
    // All items are layoued in a grid, this indicates the cell they are in
    // will be converted to screen coordinates later
    NSUInteger col;
    NSUInteger row;
    
    NSArray *existingTypeNames=[typeNamesInRow allKeys];
    if([[typeNamesInRow allKeys] containsObject:type.name]) {
      // This item already exists
      row=[[typeNamesInRow objectForKey:type.name] unsignedIntValue];
      col=[[numTypeNamesInRow objectForKey:type.name] unsignedIntValue];
    } else {
      // This item doesn't exist, so add it as a new row
      row=existingTypeNames.count;
      col=0;
      
      // Don't forget to record it
      [typeNamesInRow setObject:[NSNumber numberWithUnsignedInt:row] forKey:type.name];
    }
    
    [numTypeNamesInRow setObject:[NSNumber numberWithUnsignedInt:(col+1)] forKey:type.name];
    
    button.frame=CGRectMake(col*(buttonWidth+10)+5,row*(buttonHeight+10),buttonWidth,buttonHeight);    

    [editItemArea addSubview:button];
  }
  
  NSUInteger totalRows=[[typeNamesInRow allKeys] count];

  [editItemArea setContentSize:CGSizeMake(editItemAreaFrame.size.width,(buttonHeight+10)*totalRows)];
}

- (IBAction)editDateTime:(id)sender {
  UIActionSheet* menu = [[UIActionSheet alloc] initWithTitle:@"Date/Time" 
                                                    delegate:self 
                                           cancelButtonTitle:@"OK" 
                                      destructiveButtonTitle:nil 
                                           otherButtonTitles:nil];
	
	UIDatePicker *pickerView = [[UIDatePicker alloc] initWithFrame:CGRectMake(0,100,0,0)];
	pickerView.datePickerMode = UIDatePickerModeDateAndTime;
  pickerView.date = run.dateTime;
  
	[menu addSubview:pickerView];
	[menu showInView:[self view]];
	[menu setBounds:CGRectMake(0,0,320,510)];
}

-(void)actionSheet:(UIActionSheet*)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
	//Find the date picker
	NSArray* subviews=[actionSheet subviews];
	for(int i=0;i<[subviews count];i++)
	{
		UIDatePicker* obj=[subviews objectAtIndex:i];
		if([obj respondsToSelector:@selector(date)])
		{
			//Date picker found, since we can get the date
			run.dateTime=[obj date];
      [self updateDateTimeButton];
		}
	}
}

- (void)editItem:(id)sender {
  if([sender isKindOfClass:[RLRecyclableItemButton class]]) {
    // Determine what item to edit
    RLRecyclableItemButton *button=(RLRecyclableItemButton *)sender;
    RLRecyclableItem *item=button.item;
    
    // Prepare undo functionality for item
    [run.managedObjectContext processPendingChanges];
    [run.managedObjectContext.undoManager beginUndoGrouping];
    
    // Prepare the view that will be used to edi it
    RLEditRecyclableItemViewController *editRecyclableItemViewController=(RLEditRecyclableItemViewController *)[[RLEditRecyclableItemViewController alloc] initWithItem:item];
    
    GPNavigationBarViewController *navigationBarViewController=[GPNavigationBarViewController new];
    navigationBarViewController.navigation.title=@"Edit Quantity";
    navigationBarViewController.subview=editRecyclableItemViewController.view;
    navigationBarViewController.navigation.leftBarButtonItem=[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel
                                                                                                           target:self 
                                                                                                          action:@selector(undoEditingItem)];
    navigationBarViewController.navigation.rightBarButtonItem=[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone
                                                                                                           target:self 
                                                                                                           action:@selector(doneEditingItem)];
    
    // Display the view
    [self presentModalViewController:navigationBarViewController 
                            animated:YES];
  }
}

- (void)undoEditingItem {
  [run.managedObjectContext processPendingChanges];
  [run.managedObjectContext.undoManager endUndoGrouping];
  [run.managedObjectContext.undoManager undoNestedGroup];
  
  [self dismissModalViewControllerAnimated:YES];
}

- (void)doneEditingItem {
  [run.managedObjectContext processPendingChanges];
  [run.managedObjectContext.undoManager endUndoGrouping];
  [self updateMoneyEarnedLabel];
  [self dismissModalViewControllerAnimated:YES];
}


- (void)dealloc {
  [dateTimeButton release];
  [editItemArea release];
  [super dealloc];
}


@end
